/**
* Copyright © 2018 深圳市巨鼎医疗设备有限公司
*/
package com.zl.websocket.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import com.zl.websocket.entity.UserInfo;
import com.zl.websocket.entity.dto.UserLoginDto;
import com.zl.websocket.entity.dto.UserLoginSuccessDto;
import com.zl.websocket.service.UserService;

/**
 * 用户服务实现
 * 
 * @author Zhouych
 * @date 2018年9月4日 下午6:07:21
 * @since JDK 1.8
 */
public class UserServiceImpl implements UserService {
	
	private static Map<String, UserInfo> userTokenMap = new ConcurrentHashMap<>();
	
	private static List<UserInfo> userList = new ArrayList<>();
	//初始化几个用户
	static {
		userList.add(new UserInfo("1", "张三", "123"));
		userList.add(new UserInfo("2", "李四", "123"));
		userList.add(new UserInfo("3", "王五", "123"));
	}

	@Override
	public UserInfo getUserInfoByToken(String token) {
		return userTokenMap.get(token);
	}

	private String createToken() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	@Override
	public UserLoginSuccessDto login(UserLoginDto loginDto) {
		for(UserInfo user : userList) {
			if(user.getUsername().equals(loginDto.getUsername()) && user.getPassword().equals(loginDto.getPassword())) {
				String token = createToken();
				userTokenMap.put(token, user);
				
				return new UserLoginSuccessDto(user.getId(), token);
			}
		}
		throw new RuntimeException("用户名或密码错误");
	}
}
